import React, {
  useRef,
  useEffect,
  useState,
  useMemo,
  useCallback,
} from "react";
import { Card, Typography, Empty, Button, Progress } from "antd";
import {
  PlayCircleOutlined,
  PauseCircleOutlined,
  ReloadOutlined,
} from "@ant-design/icons";
import Draggable, { DraggableData, DraggableEvent } from "react-draggable";
import { motion, AnimatePresence } from "framer-motion";
import { getAnimationVariants } from "@/utils/animationUtils";
import GuideLines from "./GuideLines";
import { Film } from "lucide-react";

const { Text } = Typography;

interface VideoPreviewPanelProps {
  currentConfig: any;
  textPosition: { x: number; y: number };
  onTextPositionChange: (position: { x: number; y: number }) => void;
}

const VideoPreviewPanel: React.FC<VideoPreviewPanelProps> = ({
  currentConfig,
  textPosition,
  onTextPositionChange,
}) => {
  const draggableRef = useRef<HTMLDivElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  const animationTimeoutRef = useRef<NodeJS.Timeout>();
  const progressIntervalRef = useRef<any>();

  const [bounds, setBounds] = useState<any>({
    left: 0,
    top: 0,
    right: 0,
    bottom: 0,
  });
  const [draggableWidth, setDraggableWidth] = useState<string | number>("auto");
  const [isDragging, setIsDragging] = useState(false);
  const [tempPosition, setTempPosition] = useState<{ x: number; y: number }>({
    x: 0,
    y: 0,
  });

  // 用于基准线计算的状态
  const [containerDimensions, setContainerDimensions] = useState({
    width: 640,
    height: 360,
  });
  const [draggableDimensions, setDraggableDimensions] = useState({
    width: 0,
    height: 0,
  });

  // 新增：动画播放控制状态
  const [isPlaying, setIsPlaying] = useState(false);
  const [animationPhase, setAnimationPhase] =
    useState<Animation_Status>("waiting");
  const [progress, setProgress] = useState(0); // 播放进度 0-100
  const [totalDuration, setTotalDuration] = useState(0); // 总时长（秒）
  // 添加移动端检测
  const [isMobile, setIsMobile] = useState(false);
  // 计算动画时间配置
  const animationTiming = useMemo(() => {
    const textStartTime = currentConfig.text?.startTime || 1; // 文本开始时间（秒）
    const textDuration = currentConfig.text?.duration || 8; // 文本持续时间（秒）
    const introDuration = currentConfig.animations?.intro?.duration || 1.5;
    const outroDuration = currentConfig.animations?.outro?.duration || 1;

    // 计算各阶段的时间点
    const introStartTime = textStartTime;
    const loopStartTime = introStartTime + introDuration;
    const outroStartTime = textStartTime + textDuration - outroDuration;
    const totalTime = textStartTime + textDuration;

    return {
      textStartTime,
      textDuration,
      introDuration,
      outroDuration,
      introStartTime,
      loopStartTime,
      outroStartTime,
      totalTime,
    };
  }, [
    currentConfig.text?.startTime,
    currentConfig.text?.duration,
    currentConfig.animations?.intro?.duration,
    currentConfig.animations?.outro?.duration,
  ]);

  // 更新总时长
  useEffect(() => {
    setTotalDuration(animationTiming.totalTime);
  }, [animationTiming.totalTime]);

  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth <= 768);
    };

    checkIsMobile();
    window.addEventListener("resize", checkIsMobile);

    return () => window.removeEventListener("resize", checkIsMobile);
  }, []);

  // 使用 useMemo 缓存计算结果 - 针对移动端优化
  let containerStyle = useMemo(() => {
    if (isMobile) {
      // 移动端：宽度占满，高度固定为较小值
      const mobileWidth = Math.min(window.innerWidth - 40, 350); // 减去padding
      const mobileHeight = Math.min(200, (mobileWidth * 9) / 16); // 保持16:9比例，但限制最大高度为200px

      return {
        width: `${mobileWidth}px`,
        height: `${mobileHeight}px`,
        backgroundColor: "#333",
        position: "relative" as const,
        overflow: "hidden" as const,
        border: "1px solid #555",
        boxShadow: "0 0 10px rgba(0,0,0,0.5)",
        margin: "0 auto", // 居中显示
      };
    } else {
      // 桌面端：保持原有逻辑
      return {
        width: `${currentConfig.canvas?.width && currentConfig.canvas?.height ? currentConfig.canvas.width / (currentConfig.canvas.height / 360) : 640}px`,
        height: "360px",
        backgroundColor: "#333",
        position: "relative" as const,
        overflow: "hidden" as const,
        border: "1px solid #555",
        boxShadow: "0 0 10px rgba(0,0,0,0.5)",
      };
    }
  }, [currentConfig.canvas?.width, currentConfig.canvas?.height]);

  // 使用 useMemo 缓存文本样式
  const baseTextStyle = useMemo(
    (): React.CSSProperties => ({
      fontSize: `${currentConfig.text?.fontSize || 16}px`,
      color: currentConfig.text?.color || "#ffffff",
      fontWeight: currentConfig.text?.isBold ? "bold" : "normal",
      fontStyle: currentConfig.text?.isItalic ? "italic" : "normal",
      textDecoration: currentConfig.text?.isUnderline ? "underline" : "none",
      opacity: currentConfig.text?.opacity ?? 1,
      letterSpacing: `${currentConfig.text?.letterSpacing || 0}px`,
      lineHeight: `${(currentConfig.text?.fontSize || 16) + (currentConfig.text?.lineSpacing || 0)}px`,
      textAlign:
        currentConfig.text?.align === 0
          ? "left"
          : currentConfig.text?.align === 2
            ? "right"
            : "center",
      whiteSpace: "pre-wrap",
      WebkitTextStroke:
        currentConfig.border?.width > 0
          ? `${currentConfig.border?.width || 0}px ${currentConfig.border?.color || "#000000"}`
          : "none",
      display: "block",
    }),
    [
      currentConfig.text?.fontSize,
      currentConfig.text?.color,
      currentConfig.text?.isBold,
      currentConfig.text?.isItalic,
      currentConfig.text?.isUnderline,
      currentConfig.text?.opacity,
      currentConfig.text?.letterSpacing,
      currentConfig.text?.lineSpacing,
      currentConfig.text?.align,
      currentConfig.border?.width,
      currentConfig.border?.color,
    ],
  );
  // hover状态 当鼠标移动到motion.div上时，添加hover效果
  const [isHovering, setIsHovering] = useState(false);

  // 使用 useMemo 缓存 motion.div 样式 - 优化拖拽性能
  const motionDivStyle = useMemo(
    (): React.CSSProperties => ({
      position: "absolute",
      width:
        typeof draggableWidth === "number"
          ? `${draggableWidth}px`
          : draggableWidth,
      cursor: isDragging ? "grabbing" : "grab", // 改进拖拽光标
      willChange: "transform", // 优化动画性能
      // 拖拽时或hover时显示边框
      border:
        isDragging || isHovering
          ? "2px dashed #1890ff"
          : "2px dashed transparent",
      borderRadius: "4px",
      transition: isDragging ? "none" : "border-color 0.2s ease", // 拖拽时禁用过渡动画
      userSelect: "none", // 防止文本选择
      touchAction: "none", // 防止移动端触摸滚动
      ...(currentConfig.background?.style !== 0 && {
        backgroundColor: currentConfig.background?.color || "transparent",
        opacity: currentConfig.background?.opacity ?? 1,
        borderRadius:
          currentConfig.background?.style === 2
            ? `${(currentConfig.background?.roundRadius || 0) * 100}%`
            : "4px",
        padding: "10px 20px",
      }),
    }),
    [
      draggableWidth,
      isDragging,
      isHovering,
      currentConfig.background?.style,
      currentConfig.background?.color,
      currentConfig.background?.opacity,
      currentConfig.background?.roundRadius,
    ],
  );

  // 处理鼠标悬停事件 - 优化性能
  const handleMouseEnter = useCallback(() => {
    if (!isDragging) {
      setIsHovering(true);
    }
  }, [isDragging]);

  const handleMouseLeave = useCallback(() => {
    if (!isDragging) {
      setIsHovering(false);
    }
  }, [isDragging]);

  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth <= 768);
    };

    checkIsMobile();
    window.addEventListener("resize", checkIsMobile);

    return () => window.removeEventListener("resize", checkIsMobile);
  }, []);

  // 使用 useMemo 缓存计算结果 - 针对移动端优化
  containerStyle = useMemo(() => {
    if (isMobile) {
      // 移动端：宽度占满，高度固定为较小值
      const mobileWidth = Math.min(window.innerWidth - 40, 350); // 减去padding
      const mobileHeight = Math.min(200, (mobileWidth * 9) / 16); // 保持16:9比例，但限制最大高度为200px

      return {
        width: `${mobileWidth}px`,
        height: `${mobileHeight}px`,
        backgroundColor: "#333",
        position: "relative" as const,
        overflow: "hidden" as const,
        border: "1px solid #555",
        boxShadow: "0 0 10px rgba(0,0,0,0.5)",
        margin: "0 auto", // 居中显示
      };
    } else {
      // 桌面端：保持原有逻辑
      return {
        width: `${currentConfig.canvas?.width && currentConfig.canvas?.height ? currentConfig.canvas.width / (currentConfig.canvas.height / 360) : 640}px`,
        height: "360px",
        backgroundColor: "#333",
        position: "relative" as const,
        overflow: "hidden" as const,
        border: "1px solid #555",
        boxShadow: "0 0 10px rgba(0,0,0,0.5)",
      };
    }
  }, [currentConfig.canvas?.width, currentConfig.canvas?.height, isMobile]);

  // 使用防抖的 bounds 计算，减少频繁计算
  const debouncedBoundsCalculation = useCallback(
    (() => {
      let timeoutId: NodeJS.Timeout;
      return () => {
        clearTimeout(timeoutId);
        timeoutId = setTimeout(() => {
          if (containerRef.current && draggableRef.current) {
            const containerRect = containerRef.current.getBoundingClientRect();

            setContainerDimensions({
              width: containerRect.width,
              height: containerRect.height,
            });

            let newDraggableWidth: string | number = containerRect.width * 0.8;

            if (
              currentConfig.background?.style !== 0 &&
              currentConfig.background?.width
            ) {
              newDraggableWidth =
                containerRect.width * currentConfig.background.width;
            }

            // 移动端时调整文本宽度
            if (isMobile) {
              newDraggableWidth = Math.min(
                typeof newDraggableWidth === "number"
                  ? newDraggableWidth
                  : parseFloat(newDraggableWidth as string),
                containerRect.width * 0.9, // 移动端占90%宽度
              );
            } else {
              newDraggableWidth = Math.min(
                typeof newDraggableWidth === "number"
                  ? newDraggableWidth
                  : parseFloat(newDraggableWidth as string),
                containerRect.width,
              );
            }

            setDraggableWidth(newDraggableWidth);

            // 简化 bounds 计算，避免 DOM 克隆
            const estimatedTextHeight =
              (currentConfig.text?.fontSize || 16) * 1.5; // 估算文本高度
            const estimatedTextWidth =
              typeof newDraggableWidth === "number" ? newDraggableWidth : 200;
            const padding = currentConfig.background?.style !== 0 ? 40 : 0; // 20px * 2

            setDraggableDimensions({
              width: estimatedTextWidth,
              height: estimatedTextHeight + padding,
            });

            setBounds({
              left: 0,
              top: 0,
              right: Math.max(0, containerRect.width - estimatedTextWidth),
              bottom: Math.max(
                0,
                containerRect.height - (estimatedTextHeight + padding),
              ),
            });
          }
        }, 100); // 100ms 防抖
      };
    })(),
    [
      currentConfig.text?.fontSize,
      currentConfig.background?.style,
      currentConfig.background?.width,
      isMobile, // 添加移动端依赖
    ],
  );

  useEffect(() => {
    debouncedBoundsCalculation();
  }, [debouncedBoundsCalculation]);

  // 优化拖拽处理函数
  const handleDragStart = useCallback(
    (e: DraggableEvent, ui: DraggableData) => {
      // 阻止默认行为
      e.preventDefault?.();
      e.stopPropagation?.();

      setIsDragging(true);
      setTempPosition(textPosition);
      setIsHovering(true); // 拖拽开始时显示边框

      // 添加全局鼠标事件监听，防止鼠标移出元素时丢失拖拽
      document.body.style.userSelect = "none";
      document.body.style.cursor = "grabbing";
    },
    [textPosition],
  );

  const handleDrag = useCallback((e: DraggableEvent, ui: DraggableData) => {
    // 阻止默认行为
    e.preventDefault?.();
    e.stopPropagation?.();

    // 使用 requestAnimationFrame 优化性能
    requestAnimationFrame(() => {
      setTempPosition({ x: ui.x, y: ui.y });
    });
  }, []);

  const handleDragStop = useCallback(
    (e: DraggableEvent, ui: DraggableData) => {
      // 阻止默认行为
      e.preventDefault?.();
      e.stopPropagation?.();

      setIsDragging(false);
      setIsHovering(false); // 拖拽结束后移除边框

      // 恢复全局样式
      document.body.style.userSelect = "";
      document.body.style.cursor = "";

      // 延迟更新父组件状态，确保拖拽完全结束
      requestAnimationFrame(() => {
        onTextPositionChange({ x: ui.x, y: ui.y });
      });
    },
    [onTextPositionChange],
  );

  // 播放控制函数
  const startAnimation = useCallback(() => {
    if (isPlaying) return;

    setIsPlaying(true);
    setProgress(0);
    setAnimationPhase("waiting");

    // 清除之前的定时器
    if (animationTimeoutRef.current) {
      clearTimeout(animationTimeoutRef.current);
    }
    if (progressIntervalRef.current) {
      clearInterval(progressIntervalRef.current);
    }

    const startTime = Date.now();

    // 进度更新器
    progressIntervalRef.current = setInterval(() => {
      const elapsed = (Date.now() - startTime) / 1000; // 已播放时间（秒）
      const newProgress = Math.min(
        (elapsed / animationTiming.totalTime) * 100,
        100,
      );
      setProgress(newProgress);

      // 根据时间更新动画阶段
      if (
        elapsed >= animationTiming.outroStartTime &&
        animationPhase !== "outro"
      ) {
        setAnimationPhase("outro");
      } else if (
        elapsed >= animationTiming.loopStartTime &&
        animationPhase !== "loop" &&
        animationPhase !== "outro"
      ) {
        setAnimationPhase("loop");
      } else if (
        elapsed >= animationTiming.introStartTime &&
        animationPhase === "waiting"
      ) {
        setAnimationPhase("intro");
      }

      // 播放结束
      if (elapsed >= animationTiming.totalTime) {
        setAnimationPhase("ended");
        setIsPlaying(false);
        setProgress(100);
        clearInterval(progressIntervalRef.current!);
        // 播放结束后延迟重置到初始状态
        setAnimationPhase("waiting");
        setProgress(0);
      }
    }, 50); // 每50ms更新一次进度
  }, [isPlaying, animationTiming, animationPhase]);

  const pauseAnimation = useCallback(() => {
    setIsPlaying(false);
    if (animationTimeoutRef.current) {
      clearTimeout(animationTimeoutRef.current);
    }
    if (progressIntervalRef.current) {
      clearInterval(progressIntervalRef.current);
    }
  }, []);

  const resetAnimation = useCallback(() => {
    setIsPlaying(false);
    setAnimationPhase("waiting");
    setProgress(0);

    // 清除所有定时器
    if (animationTimeoutRef.current) {
      clearTimeout(animationTimeoutRef.current);
    }
    if (progressIntervalRef.current) {
      clearInterval(progressIntervalRef.current);
    }
    // 通过更新key来强制重新渲染
    setTimeout(() => {
      setAnimationPhase("waiting");
    }, 50);
  }, []);

  // 清理定时器
  useEffect(() => {
    return () => {
      if (animationTimeoutRef.current) {
        clearTimeout(animationTimeoutRef.current);
      }
      if (progressIntervalRef.current) {
        clearInterval(progressIntervalRef.current);
      }
    };
  }, []);

  // 使用 useMemo 缓存动画相关计算
  const animationConfig = useMemo(() => {
    const {
      intro: introAnim,
      outro: outroAnim,
      loop: loopAnim,
    } = currentConfig.animations || {};

    const animationVariants = getAnimationVariants(
      introAnim?.type,
      introAnim?.duration || 1.5,
      loopAnim?.type,
      outroAnim?.type,
      outroAnim?.duration || 1,
    );

    let activeVariants;

    if (isDragging) {
      // 拖拽时保持简单状态
      activeVariants = {
        initial: { opacity: 1 },
        animate: { opacity: 1 },
        exit: { opacity: 1 },
      };
    } else {
      // 根据动画阶段决定变体
      switch (animationPhase) {
        case "waiting":
          activeVariants = {
            initial: animationVariants.initial || { opacity: 0 },
            animate: animationVariants.initial || { opacity: 0 },
            exit: animationVariants.initial || { opacity: 0 },
          };
          break;
        case "intro":
          activeVariants = {
            initial: animationVariants.initial || { opacity: 0 },
            animate: animationVariants.animate || { opacity: 1 },
            exit: animationVariants.animate || { opacity: 1 },
          };
          break;
        case "loop":
          activeVariants = {
            initial: animationVariants.animate || { opacity: 1 },
            animate: animationVariants.animate || { opacity: 1 },
            exit: animationVariants.animate || { opacity: 1 },
          };
          break;
        case "outro":
          activeVariants = {
            initial: animationVariants.animate || { opacity: 1 },
            animate: animationVariants.exit || { opacity: 0 },
            exit: animationVariants.exit || { opacity: 0 },
          };
          break;
        case "ended":
          // 播放结束状态 - 确保完全隐藏
          activeVariants = {
            initial: { opacity: 0 },
            animate: { opacity: 0 },
            exit: { opacity: 0 },
          };
          break;
        default:
          activeVariants = animationVariants;
      }
    }

    // 添加时间戳确保key的唯一性，特别是在重置时
    const animationKey = `${currentConfig.text?.content}-${introAnim?.type}-${loopAnim?.type}-${outroAnim?.type}-${currentConfig.text?.fontSize}-${currentConfig.text?.color}-${currentConfig.background?.color}-${animationPhase}-${Date.now()}`;

    return { activeVariants, animationKey };
  }, [
    currentConfig.animations,
    currentConfig.text?.content,
    currentConfig.text?.fontSize,
    currentConfig.text?.color,
    currentConfig.background?.color,
    isDragging,
    animationPhase,
  ]);

  // 拖拽时使用临时位置，非拖拽时使用实际位置
  const currentPosition = isDragging ? tempPosition : textPosition;

  // 渲染播放控制区域 - 移动到蓝框位置
  const renderPlayControls = () => (
    <div
      style={{
        width: "100%",
        padding: isMobile ? "12px" : "16px", // 移动端减少padding
        background: "rgba(0, 0, 0, 0.8)",
        backdropFilter: "blur(4px)",
        borderTop: "1px solid rgba(255, 255, 255, 0.1)",
      }}
    >
      <div
        style={{
          display: "flex",
          alignItems: "center",
          gap: isMobile ? "8px" : "12px", // 移动端减少间距
          justifyContent: "center",
          flexWrap: isMobile ? "wrap" : "nowrap", // 移动端允许换行
        }}
      >
        {/* 播放/暂停按钮 */}
        {!isPlaying ? (
          <Button
            type="primary"
            icon={<PlayCircleOutlined />}
            onClick={startAnimation}
            size={isMobile ? "small" : "small"}
          >
            {isMobile ? "" : "播放"} {/* 移动端只显示图标 */}
          </Button>
        ) : (
          <Button
            icon={<PauseCircleOutlined />}
            onClick={pauseAnimation}
            size={isMobile ? "small" : "small"}
          >
            {isMobile ? "" : "暂停"} {/* 移动端只显示图标 */}
          </Button>
        )}

        {/* 重置按钮 */}
        <Button
          icon={<ReloadOutlined />}
          onClick={resetAnimation}
          size={isMobile ? "small" : "small"}
          disabled={!isPlaying && progress === 0}
        >
          {isMobile ? "" : "重置"} {/* 移动端只显示图标 */}
        </Button>

        {/* 进度条 */}
        <div
          style={{
            flex: 1,
            maxWidth: isMobile ? "120px" : "200px",
            minWidth: isMobile ? "80px" : "120px",
          }}
        >
          <Progress
            percent={progress}
            size="small"
            showInfo={false}
            strokeColor="#1890ff"
          />
        </div>

        {/* 时间显示 */}
        <div
          style={{
            color: "white",
            fontSize: isMobile ? "11px" : "12px",
            minWidth: isMobile ? "60px" : "80px",
            textAlign: "center",
          }}
        >
          {((progress / 100) * totalDuration).toFixed(1)}s /{" "}
          {totalDuration.toFixed(1)}s
        </div>

        {/* 阶段指示器 - 移动端可隐藏或简化 */}
        {!isMobile && (
          <div style={{ color: "white", fontSize: "12px", minWidth: "40px" }}>
            {animationPhase === "waiting" && "准备"}
            {animationPhase === "intro" && "入场"}
            {animationPhase === "loop" && "循环"}
            {animationPhase === "outro" && "出场"}
            {animationPhase === "ended" && "结束"}
          </div>
        )}
      </div>
    </div>
  );

  // 移动端配置信息显示组件
  const renderMobileConfigInfo = () => (
    <div
      style={{
        textAlign: "center",
        height: "100%",
        display: "flex",
        flexDirection: "column",
        justifyContent: "center",
        alignItems: "center",
        background: "linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)",
        borderRadius: "2px", // 设置为2px
      }}
    >
      {/* 提示图标和标题 */}
      <div style={{ marginBottom: "20px" }}>
        <Film size={48} color="#1890ff" style={{ marginBottom: "12px" }} />
        <h3 style={{ margin: 0, color: "#1890ff", fontSize: "18px" }}>
          移动端预览暂不支持
        </h3>
        <p
          style={{
            margin: "8px 0 0 0",
            color: "#666",
            fontSize: "14px",
            lineHeight: "1.5",
          }}
        >
          请生成脚本后导入剪映查看效果
        </p>
      </div>

      {/* 当前配置信息 */}
      <div
        style={{
          background: "rgba(255, 255, 255, 0.9)",
          borderRadius: "2px", // 设置为2px
          padding: "16px",
          width: "100%",
          maxWidth: "90%", // 从300px改为90%，让它更宽
          textAlign: "left",
          boxShadow: "0 2px 8px rgba(0, 0, 0, 0.1)",
        }}
      >
        <h4
          style={{
            margin: "0 0 12px 0",
            color: "#1890ff",
            fontSize: "14px",
            textAlign: "center",
          }}
        >
          当前配置信息
        </h4>

        <div style={{ fontSize: "12px", lineHeight: "1.6", color: "#333" }}>
          <div style={{ marginBottom: "8px" }}>
            <strong>画布尺寸：</strong>
            {currentConfig.canvas?.width || 1920} ×{" "}
            {currentConfig.canvas?.height || 1080}
          </div>

          <div style={{ marginBottom: "8px" }}>
            <strong>文本内容：</strong>
            <span
              style={{
                color: "#666",
                display: "block",
                marginTop: "2px",
                maxHeight: "40px",
                overflow: "hidden",
                textOverflow: "ellipsis",
                whiteSpace: "nowrap",
              }}
            >
              {currentConfig.text?.content || "未设置"}
            </span>
          </div>

          <div style={{ marginBottom: "8px" }}>
            <strong>字体大小：</strong>
            {currentConfig.text?.fontSize || 16}px
          </div>

          <div style={{ marginBottom: "8px" }}>
            <strong>文本颜色：</strong>
            <span
              style={{
                display: "inline-block",
                width: "16px",
                height: "16px",
                backgroundColor: currentConfig.text?.color || "#ffffff",
                border: "1px solid #ddd",
                borderRadius: "2px", // 设置为2px
                marginLeft: "4px",
                verticalAlign: "middle",
              }}
            ></span>
            <span
              style={{ marginLeft: "4px", fontSize: "11px", color: "#666" }}
            >
              {currentConfig.text?.color || "#ffffff"}
            </span>
          </div>

          <div style={{ marginBottom: "8px" }}>
            <strong>动画效果：</strong>
            {currentConfig.animations?.intro?.type || "无"} →{" "}
            {currentConfig.animations?.outro?.type || "无"}
          </div>

          <div style={{ marginBottom: "8px" }}>
            <strong>视频素材：</strong>
            {currentConfig.videos?.length || 0} 个
          </div>

          <div>
            <strong>总时长：</strong>
            {currentConfig.text?.duration || 8} 秒
          </div>
        </div>
      </div>

      {/* 操作提示 */}
      <div
        style={{
          marginTop: "16px",
          padding: "12px",
          background: "rgba(24, 144, 255, 0.1)",
          borderRadius: "2px", // 设置为2px
          width: "100%",
          maxWidth: "90%", // 从300px改为90%，让它更宽
        }}
      >
        <p
          style={{
            margin: 0,
            fontSize: "12px",
            color: "#1890ff",
            textAlign: "center",
            lineHeight: "1.4",
          }}
        >
          💡 在移动端可以配置项目参数，
          <br />
          完成后点击"创建项目"生成脚本
        </p>
      </div>
    </div>
  );

  return (
    <Card
      title={isMobile ? "项目概览" : "实时预览"}
      size="small"
      style={{
        height: "100%",
        flexGrow: 1,
        margin: 0,
        borderRadius: 0,
        overflow: "hidden",
        display: "flex",
        flexDirection: "column",
        backgroundColor: "transparent", // 设置为透明
        border: "none", // 移除边框
      }}
      bodyStyle={{
        flex: 1,
        overflow: "hidden",
        padding: isMobile ? "0" : 0,
        display: "flex",
        flexDirection: "column",
        background: isMobile ? "#f8f9fa" : "transparent",
      }}
      headStyle={{
        borderBottomColor: "#fff",
        backgroundColor: "black",
        borderBottom: "1px solid #3d3d3d",
        color: "#ffffff",
      }}
    >
      {/* 移动端显示配置信息，桌面端显示预览 */}
      {isMobile ? (
        renderMobileConfigInfo()
      ) : (
        <>
          {/* 预览区域 */}
          <div
            style={{
              flex: 1,
              display: "flex",
              alignItems: "center",
              justifyContent: "center",
              position: "relative",
              background: "transparent", // 设置为透明让父容器的背景显示
            }}
          >
            <div ref={containerRef} style={containerStyle}>
              {/* 基准线组件 */}
              <GuideLines
                containerWidth={containerDimensions.width}
                containerHeight={containerDimensions.height}
                draggableX={currentPosition.x}
                draggableY={currentPosition.y}
                draggableWidth={draggableDimensions.width}
                draggableHeight={draggableDimensions.height}
                isDragging={isDragging}
              />

              {currentConfig.text?.content ? (
                <AnimatePresence mode="wait" initial={false}>
                  <Draggable
                    key={`draggable-${animationConfig.animationKey}`}
                    nodeRef={draggableRef}
                    position={currentPosition}
                    onStart={handleDragStart}
                    onDrag={handleDrag}
                    onStop={handleDragStop}
                    bounds={bounds}
                    enableUserSelectHack={false}
                    defaultClassNameDragging=""
                    defaultClassNameDragged=""
                    // 添加拖拽配置优化
                    handle={undefined} // 整个元素都可拖拽
                    cancel="" // 不取消任何子元素的拖拽
                    grid={[1, 1]} // 设置最小拖拽单位为1px
                    scale={1} // 不缩放
                    allowAnyClick={false} // 只允许左键拖拽
                  >
                    <div
                      style={motionDivStyle}
                      onMouseEnter={handleMouseEnter}
                      onMouseLeave={handleMouseLeave}
                      // 添加拖拽优化属性
                      onDragStart={(e) => e.preventDefault()} // 防止浏览器默认拖拽
                      // @ts-ignore
                      onSelectStart={(e) => e.preventDefault()} // 防止文本选择
                    >
                      <motion.div
                        ref={draggableRef}
                        key={animationConfig.animationKey}
                        variants={animationConfig.activeVariants}
                        initial="initial"
                        animate="animate"
                        exit="exit"
                        transition={
                          isDragging
                            ? { duration: 0 } // 拖拽时禁用动画
                            : animationPhase === "intro"
                              ? { duration: animationTiming.introDuration }
                              : animationPhase === "outro"
                                ? { duration: animationTiming.outroDuration }
                                : animationPhase === "waiting" ||
                                    animationPhase === "ended"
                                  ? { duration: 0.3 } // 等待和结束状态快速过渡
                                  : undefined
                        }
                        layout={!isDragging} // 拖拽时禁用layout动画
                        // 添加拖拽时的样式优化
                        style={{
                          pointerEvents: isDragging ? "none" : "auto", // 拖拽时禁用子元素事件
                        }}
                        // 添加动画完成回调
                        onAnimationComplete={() => {
                          // 当动画完成且处于ended状态时，确保重置
                          if (animationPhase === "ended" && !isPlaying) {
                            setTimeout(() => {
                              setAnimationPhase("waiting");
                              setProgress(0);
                            }, 500);
                          }
                        }}
                      >
                        <Text
                          style={{
                            ...baseTextStyle,
                            pointerEvents: "none", // 防止文本干扰拖拽
                          }}
                        >
                          {currentConfig.text.content}
                        </Text>
                      </motion.div>
                    </div>
                  </Draggable>
                </AnimatePresence>
              ) : (
                <div
                  style={{
                    textAlign: "center",
                    color: "#fff",
                    width: "100%",
                    height: "100%",
                    display: "flex",
                    alignItems: "center",
                    justifyContent: "center",
                  }}
                >
                  <Empty
                    description="请输入文本内容以预览"
                    image={Empty.PRESENTED_IMAGE_SIMPLE}
                  />
                </div>
              )}
            </div>
          </div>

          {/* 播放控制区域 - 只在桌面端显示 */}
          {currentConfig.text?.content && renderPlayControls()}
        </>
      )}

      {/* 移动端响应式样式 */}
      <style>{`
        /* 自定义卡片标题样式 */
        @media (max-width: 768px) {
          .ant-card-head {
            padding: 0 12px !important;
            min-height: 40px !important;
            background-color: #667eea !important;
          }
          .ant-btn {
            min-width: auto !important;
          }
          
          .ant-btn-sm {
            height: 28px !important;
            padding: 0 8px !important;
          }
        }
        
        @media (max-width: 576px) {
          .ant-card-body {
            padding: 0 !important;
          }
        }

        /* 拖拽元素hover效果 */
        .draggable-text-element:hover {
          border: 2px dashed #1890ff !important;
          box-shadow: 0 0 8px rgba(24, 144, 255, 0.3);
        }

        /* 优化拖拽性能 */
        .react-draggable {
          transform: translate3d(0, 0, 0); /* 启用GPU加速 */
        }
        
        .react-draggable-dragging {
          z-index: 1000; /* 拖拽时提升层级 */
        }
        
        /* 防止拖拽时的闪烁 */
        .react-draggable-dragging * {
          pointer-events: none !important;
        }
      `}</style>
    </Card>
  );
};

export default VideoPreviewPanel;
